<template>
  <a-select v-model:value="selected">
    <a-select-option v-for="option in options" :key="option.uid" :value="option.uid">{{
      option.name
    }}</a-select-option>
  </a-select>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, watch } from 'vue'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { AccountingSubjectData } from '@/api/chunfeng/accounting/interfaces'
import { useAccountingApi } from '@/api/chunfeng/accounting'

export default defineComponent({
  name: 'AccountingSubjectSelection',
  props: {
    accountingType: {
      type: String,
      required: true,
      default: 'income',
    },
  },
  emits: ['accountingSubjectSelected'],
  setup(props, context) {
    const selected = ref('')
    const options = ref(Array<AccountingSubjectData>())

    watch(selected, (newValue) => {
      context.emit('accountingSubjectSelected', newValue)
    })

    watch(
      () => props.accountingType,
      () => {
        reset()
        update()
      },
    )

    const { executeQueryRequest } = useHttpRequest()
    const { queryAccountingSubject } = useAccountingApi()

    function update() {
      options.value.length = 0
      executeQueryRequest(
        queryAccountingSubject({ enabled: true, type: props.accountingType }),
        (data: AccountingSubjectData[]) => {
          options.value.push(...data)
        },
      )
    }
    function reset() {
      selected.value = ''
    }

    update()

    return {
      selected,
      options,
      reset,
    }
  },
})
</script>

<style scoped>
.brand-select {
  width: 70px;
}
</style>
